package web.server.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class JsonHelper {

    private static ObjectMapper objectMapper = new ObjectMapper();

    public static String beanToJson(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     *
     * json字符串转java对象
     *
     * @param jsonString        json字符串
     * @param targetClazz       期望类型
     * @param <T>               泛型
     * @return                  java对象
     */
    public static <T> T jsonObjectToJavaObject(String jsonString, Class<?> targetClazz){

        T t = null;
        try {
            t = (T) objectMapper.readValue(jsonString, targetClazz);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return t;
    }

}
